package com.wuwei.elearning.question.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.elearning.question.domain.Ppt;
import com.wuwei.elearning.question.domain.Video;
import com.wuwei.elearning.question.mapper.VideoMapper;
import com.wuwei.elearning.question.service.VideoService;
import com.wuwei.elearning.utils.MinioUtil;
import com.wuwei.elearning.utils.result.Result;
import io.minio.GetObjectResponse;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/elearning/video")
@CrossOrigin
public class VideoController {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private VideoMapper videoMapper;

    @GetMapping("list/{name}/{currentPage}/{pageSize}")
    public Result<List<Video>> getVideos(@PathVariable("name")String name, @PathVariable("currentPage") int currentPage,
                                     @PathVariable("pageSize") int pageSize) {
        return Result.ok(videoService.selectList(name,currentPage,pageSize));
    }

    @GetMapping("getTotal/{name}")
    public Result<Long> getTotal(@PathVariable("name")String name){
        return Result.ok(videoService.selectTotal(name));
    }

    @PostMapping("deleteByURL")
    public Result<String> deleteByURL(@RequestBody Video Video) {
        videoService.deleteByUrl(Video);
        return Result.ok("删除成功！");
    }

    @SneakyThrows
    @PostMapping("uploadVideo")
    public void uploadVideo(MultipartFile file, HttpServletResponse response){
        if (file.getSize() != 0) {
            String originalFilename = file.getOriginalFilename();
            int indexOfPoint = 0;
            if (originalFilename != null) {
                indexOfPoint = originalFilename.lastIndexOf(".");
                if (indexOfPoint==-1)  {
                    Result.sendErrorResponse(response, "文件名不合法！", HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                Long count = videoService.selectCount(originalFilename);
                if (count > 0) {
                    Result.sendErrorResponse(response, "文件名重复！", HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
                String upperCase = suffix.toUpperCase();
                String mp4 = "mp4".toUpperCase();
                String avi = "avi".toUpperCase();
                if (!avi.equals(upperCase)&&!mp4.equals(upperCase)) {
                    Result.sendErrorResponse(response,"请选择mp4或avi格式的课件！",HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                videoService.uploadVideo(file);
            } else {
                Result.sendErrorResponse(response, "文件名不合法！", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        } else {
            Result.sendErrorResponse(response,"您没有上传任何文件", HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    @Resource
    private VideoService videoService;

    @GetMapping("getAll")
    public Result<List<Video>> getAll(){
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        //这里筛选条件是；筛选video中url不为null或空字符串且duration不为null
        wrapper.isNotNull(Video::getUrl)
                .ne(Video::getUrl, "")
                .isNotNull(Video::getDuration);
        List<Video> videos = videoService.list(wrapper);
        return Result.ok(videos);
    }

    @GetMapping("/stream")
    public ResponseEntity<StreamingResponseBody> streamVideo(@RequestParam String fileName) {
        GetObjectResponse object = minioUtil.getObject(fileName);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("video/mp4"));

        // 创建流式响应
        StreamingResponseBody responseBody = outputStream -> {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = object.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            object.close();
        };

        return ResponseEntity.ok()
                .headers(headers)
                .body(responseBody);
    }

}
